package com.effects;

import com.effects.ext.ExtPoint;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author sad
 */
public class CirclesEffect extends BasicEffect {

    private final double[] equalizer = new double[8];
    private ExtPoint[] circles = new ExtPoint[20];
    private static int counter = 0;
    @Override
    public String getEffectName() {
        return "Circles";
    }

    @Override
    public String getId() {
        return "circles";
    }

    public CirclesEffect() {
        for (int i = 0; i < circles.length; i++) {
            double x = Math.random() * 78;
            double y = Math.random() * 39;
            circles[i] = new ExtPoint((int) x, (int) y);
            circles[i].setxStep((Math.random()-0.5>0?1:-1));
            circles[i].setyStep((Math.random()-0.5>0?1:-1));
        }
    }

    @Override
    public BufferedImage getImage(byte[] pcm) {
        spectrum(pcm);

        double factor = spectrum.length / equalizer.length;
        int sample = 0;
        for (int j = 0; j < equalizer.length; j++, sample += factor) {
            equalizer[j] = spectrum[sample];
        }

        Graphics g = image.getGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());
        g.setColor(Color.BLUE);


        for (int i = 0; i < equalizer.length; i++) {
            double r = equalizer[i];
            r = r * 10 ;
            g.setColor(rainbow[(int) (equalizer[i] * 72)]);
            ExtPoint p = circles[i];
            drawCircle(g, (int) p.getX(), (int) p.getY(), (int) r);

            if (counter++%5==0) {
                p.setLocation(p.getX() + p.getxStep(), p.getY() + p.getyStep());

                p.setLocation(p.getX() + p.getxStep(), p.getY() + p.getyStep());

                if (p.getY()>=39){
                    p.setyStep(-p.getyStep());
                    p.setLocation(p.getX(),39);
                }
                if (p.getY()<=0){
                    p.setyStep(-p.getyStep());
                    p.setLocation(p.getX(),0);
                }
                if (p.getX()>=78){
                    p.setxStep(-p.getxStep());
                    p.setLocation(78,p.getY());
                }
                if (p.getX()<=0){
                    p.setxStep(-p.getxStep());
                    p.setLocation(0,p.getY());
                }
            }

        }

        return image;
    }

    private void drawCircle(Graphics g, int x, int y, int radius) {
        g.fill3DRect(x,y, radius*2, radius*2, true);
    }
}
